<template>
  <div class="favorites-container">
    <h3>我的收藏</h3>
    <div class="favorite-post" v-for="post in favoritePosts" :key="post.knowledgeId">
      <div class="post-title">{{ post.title }}</div>
      <div class="post-meta">
        <span>作者: {{ post.author }}</span>
        <span>收藏时间: {{ formatDate(post.createdAt) }}</span>
      </div>
      <div class="post-actions">
        <button @click="viewDetail(post.knowledgeId)">查看详情</button>
        <button @click="toggleFavorite(post.knowledgeId)">取消收藏</button>
      </div>
    </div>
    <div v-if="!favoritePosts.length" class="empty-favorite">暂无收藏</div>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { usePostStore } from '@/stores/post'

const router = useRouter()
const userStore = useUserStore()
const postStore = usePostStore()

const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

const favoritePosts = computed(() =>
  postStore.allPosts.filter(post =>
    post.favoritedBy?.includes(String(userStore.user?.userId))
  )
)

const viewDetail = (id) => {
  router.push({ name: 'PostDetail', params: { id } })
}

const toggleFavorite = (id) => {
  if (!userStore.user?.userId) return
  postStore.toggleFavorite(id, userStore.user.userId)
}
</script>

<style scoped>
.favorite-post {
  margin-bottom: 15px;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  background: #fcfcfc;
}
.post-title {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 5px;
}
.post-meta {
  font-size: 13px;
  color: #666;
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}
.post-actions button {
  margin-right: 10px;
}
.empty-favorite {
  text-align: center;
  color: #aaa;
  margin-top: 20px;
}
</style>
